package user

import (
	"encoding/json"
	"fmt"
	"github.com/gofiber/fiber/v2"
	"go-fiber-demo/pkg"
	"go-fiber-demo/pkg/utils/encoder/aes"
	"go-fiber-demo/pkg/utils/encoder/jwt"
	userService "go-fiber-demo/services/user"
)

type LoginFormData struct {
	Username string `json:"username" xml:"username" form:"username"`
	Password string `json:"password" xml:"password" form:"password"`
}

// 登录
func Login(ctx *fiber.Ctx) error {
	response := new(pkg.Response)

	loginData := new(LoginFormData)

	if err := ctx.BodyParser(loginData); err != nil {
		response.Status = -1
		response.Message = err.Error()
		return ctx.JSON(response)
	}

	user, err := userService.Login(loginData.Username, loginData.Password)

	if err != nil {
		response.Status = -1
		response.Message = err.Error()
	} else {
		fullPermissions := user.FullPermissions()
		fmt.Println(fullPermissions)
		// 登录成功后返回 token
		data := map[string]interface{}{
			"uid": user.ID,
		}

		dataBytes, err := json.Marshal(data)
		if err != nil {
			response.Status = -2
			response.Message = err.Error()
		}

		data["token"] = aes.CbcEncodeBytes(dataBytes)

		token, err := jwt.Encoding(data)
		if err != nil {
			return ctx.Status(503).SendString("JWT Token 生成失败，联系管理员。" + err.Error())
		}
		response.Data = token
		response.Message = "登录成功"
	}

	return ctx.JSON(response)
}
